package ext.generic.part;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import wt.csm.navigation.ClassificationNode;
import wt.fc.ObjectIdentifier;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.httpgw.GatewayServletHelper;
import wt.httpgw.URLFactory;
import wt.iba.value.FloatValue;
import wt.iba.value.StringValue;
import wt.inf.container.WTContainer;
import wt.inf.sharing.DataSharingHelper;
import wt.ixb.handlers.netmarkets.JSPFeedback;
import wt.ixb.handlers.netmarkets.NmFeedbackSpec;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.part.LineNumber;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.pom.Transaction;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionContext;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;
import wt.vc.baseline.ManagedBaseline;
import wt.vc.config.ConfigSpec;
import wt.vc.views.View;
import wt.workflow.work.WorkItem;

import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.core.query.report.bom.common.BOMReportHelper;
import com.ptc.core.query.report.bom.server.RecursiveStructureError;
import com.ptc.netmarkets.model.NmChangeModel;
import com.ptc.netmarkets.model.NmException;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmClipboardBean;
import com.ptc.netmarkets.util.beans.NmClipboardUtility;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.netmarkets.util.misc.NmContext;
import com.ptc.netmarkets.util.misc.NmWizardConfirm;
import com.ptc.windchill.enterprise.part.reports.ReportInfo;
import com.ptc.windchill.enterprise.part.reports.ReportRow;

import ext.com.iba.IBAUtil;
import ext.com.org.OrgUtil;
/**
 * 有关零部件的一些JSP页面上数据获取或处理的方法类
 */
public class PartCommands implements RemoteAccess
{
    private static String CLASSNAME = PartCommands.class.getName();
    private static boolean VERBOSE = false;
    private static WTProperties wtProperties = null;
    static
    {
        try
        {
            wtProperties = WTProperties.getLocalProperties();
            VERBOSE = wtProperties.getProperty("ext.generic.part.verbose", false);
        }
        catch (Throwable throwable)
        {
            throw new ExceptionInInitializerError(throwable);
        }
    }

    public PartCommands()
    {
        super();
    }

    /**
     *为流程页面获取相关打印对象列表
     * @param commandBean
     * @return
     * @throws WTException
     */
    public static Vector getPrintObjectsForWorkflow(NmCommandBean commandBean) throws WTException
    {
        Vector printObjects = new Vector();
        printObjects = (Vector) commandBean.getMap().get("printObjects");
        if (VERBOSE)
            System.out.println("    print objects from session cache==" + printObjects);
        if (printObjects != null)
        {
            if (VERBOSE)
                System.out.println("    got print objects from session cache.");
            return printObjects;
        }
        if (!RemoteMethodServer.ServerFlag)
        {
            String method = "getPrintObjectsForWorkflow";
            try
            {
                return (Vector) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[]
                        { NmCommandBean.class }, new Object[]
                        { commandBean });
            }
            catch (Exception exp)
            {
                exp.printStackTrace();
            }
        }
        //获取PBO
        NmOid oid = commandBean.getActionOid();
        WorkItem workitem = (WorkItem) oid.getRefObject();
        printObjects = PartWorkflowUtil.getPrintObjects(workitem);
        return printObjects;
    }
    /**
     *复制对象
     * @param nmcommandbean
     * @return
     * @throws WTException
     */
    public static FormResult list_copy(NmCommandBean nmcommandbean) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".list_copy()");
        ArrayList arraylist = new ArrayList();
        ArrayList arraylist1 = nmcommandbean.getSelected();
        if (arraylist1 == null || arraylist1.size() <= 0)
        {
            arraylist1 = nmcommandbean.getSelectedInOpener();
            if (VERBOSE)
                System.out.println("    nmcommandbean.getSelectedInOpener()==" + arraylist1);
        }
        else
        {
            if (VERBOSE)
                System.out.println("    nmcommandbean.getSelected()  count==" + arraylist1.size());
        }

        if (nmcommandbean.getRequest().getParameter("cut") == null)
        {
            Iterator iterator = arraylist1.iterator();
            while (iterator.hasNext())
            {
              Object obj = iterator.next();
              NmOid nmoid = NmCommandBean.getOidFromObject(obj);
              if (nmoid.isA(ManagedBaseline.class))
              {
                arraylist.add(obj);
              }
            }
            arraylist1.removeAll(arraylist);
        }
        return doCopy(nmcommandbean, arraylist1);
    }
    /**
     *复制对象的子方法
     * @param nmcommandbean
     * @param arraylist
     * @return
     * @throws WTException
     */
    private static FormResult doCopy(NmCommandBean nmcommandbean, ArrayList arraylist) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doCopy()");
        FormResult formResult = new FormResult();
        formResult.setStatus(FormProcessingStatus.SUCCESS);

        if ((arraylist == null || arraylist.size() == 0) && nmcommandbean.getRequest().getParameter("clippedObjects") == null)
        {
            formResult.setNextAction(FormResultAction.NONE);
            return formResult;
        }
        NmClipboardBean nmclipboardbean = nmcommandbean.getClipboardBean();
        if (nmcommandbean.getRequest().getParameter("clippedObjects") != null)
        {
            String s = nmcommandbean.getRequest().getParameter("clippedObjects");
            List list = NmClipboardUtility.decodeFromString(s);
            nmclipboardbean.add(list);
        }
        else
        {
            if (nmcommandbean.getRequest().getParameter("cut") != null)
            {
                WTContainer wtcontainer = nmcommandbean.getViewingContainer();
                if (wtcontainer != null)
                {
                    NmOid nmoid = new NmOid(wtcontainer);
                    Iterator iterator = arraylist.iterator();
                    while (iterator.hasNext())
                    {
                      Object obj = iterator.next();
                      NmOid nmoid1 = NmCommandBean.getOidFromObject(obj);
                      Object obj1 = nmoid1.getRef();
                      if ((!(obj1 instanceof ClassificationNode)) && 
                        ((obj1 instanceof Persistable)) && (DataSharingHelper.isShared((Persistable)obj1)))
                      {
                        if ((obj instanceof NmOid))
                        {
                          ((NmOid)obj).setSharedContainer(nmoid);
                        }
                        else if ((obj instanceof NmContext))
                        {
                          ((NmContext)obj).getTargetOid().setSharedContainer(nmoid);
                        }
                      }
                    }
                }
            }
            nmcommandbean.setClipped(arraylist);
            System.out.println("	add the " + arraylist.size() + " objects into Clipped cache.");
        }
        formResult.setNextAction(FormResultAction.NONE);
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doCopy()");
        return formResult;
    }

    /**
     *客制化的零部件报表excel格式
     * @param nmcommandbean
     * @throws WTException
     * @throws WTPropertyVetoException
     */
    public static URL exportPartReportToExcel(NmCommandBean nmcommandbean) throws WTException, WTPropertyVetoException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".exportPartReportToExcel()");
        URL url = null;
        if (!RemoteMethodServer.ServerFlag)
        {
            try
            {
                //获取配置规范
                NmOid oid = nmcommandbean.getPrimaryOid();
                HttpServletRequest request = nmcommandbean.getRequest();
                HttpSession session = request.getSession();

                ConfigSpec configSpec = null;

                String hostName = request.getRemoteHost();
                if (hostName != null)
                    hostName = request.getRemoteAddr();
                String cookieName = "PartStructure-wt.part.WTPart:" + oid.getOidObject().getId();
                if (session != null && hostName != null && cookieName != null)
                {
                    configSpec = BOMReportHelper.getConfigSpecFromCookie(hostName, session.getId(), cookieName);
                }

                //System.out.println("    configSpec=" + configSpec);
                //结束获取配置规范
                Class aclass[] =
                { NmCommandBean.class, ConfigSpec.class };
                Object aobj[] =
                { nmcommandbean, configSpec };
                url = (URL) RemoteMethodServer.getDefault().invoke("exportPartReportToExcel", CLASSNAME, null, aclass, aobj);
                refreshFromToolbarAction(nmcommandbean, url);
                return url;
            }
            catch (InvocationTargetException invocationtargetexception)
            {
                Throwable throwable = invocationtargetexception.getTargetException();
                if (throwable instanceof WTException)
                {
                    throw (WTException) throwable;
                }
                else
                {
                    Object aobj2[] =
                    { "exportPartReportToExcel" };
                    throw new WTException(throwable, "wt.fc.fcResource", "0", aobj2);
                }
            }
            catch (RemoteException remoteexception)
            {
                Object aobj1[] =
                { "exportPartReportToExcel" };
                throw new WTException(remoteexception, "wt.fc.fcResource", "0", aobj1);
            }
            catch (IOException ioe)
            {
                throw new WTException(ioe);
            }
        }
        ReportExporter exporter = new ReportExporter();
        url = exporter.exportPartReportToExcel(nmcommandbean);
        return url;
    }

    /**
     *客制化零部件报表excel格式
     * @param nmcommandbean
     * @throws WTException
     * @throws WTPropertyVetoException
     */
    public static URL exportPartReportToExcel(NmCommandBean nmcommandbean, ConfigSpec configSpec) throws WTException, WTPropertyVetoException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".exportPartReportToExcel(NmCommandBean nmcommandbean, ConfigSpec configSpec)");
        URL url = null;
        ReportExporter exporter = new ReportExporter();
        url = exporter.exportPartReportToExcel(nmcommandbean, configSpec);
        return url;
        //refreshFromPopup(nmcommandbean, url);
    }


    /**
     *导入Proe明细表(CSV格式),并依此更新BOM中的行号和数量
     * @param nmcommandbean
     * @return
     * @throws WTException
     * @throws WTPropertyVetoException
     */
    public static NmChangeModel[] updateLineNumberFromProeBOMTable(NmCommandBean nmcommandbean) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".updateLineNumberFromProeBOMTable()");
        HttpServletRequest httpservletrequest = nmcommandbean.getRequest();
        File file = (File) httpservletrequest.getAttribute("file");
        String s = null;
        if (file != null)
        {
            s = file.getAbsolutePath();
        }
        try
        {
            doUpdateLineNumberFromProeBOMTable(nmcommandbean, s);
        }
        catch (NmWizardConfirm nmwizardconfirm)
        {
            throw nmwizardconfirm;
        }
        file.delete();
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".updateLineNumberFromProeBOMTable()");
        return null;
    }

    /**
     *服务端方法:导入Proe明细表(CSV格式),并依此更新BOM中的行号和数量
     * @param nmcommandbean
     * @param excelFilePath
     * @return
     * @throws WTException
     */
    public static NmChangeModel[] doUpdateLineNumberFromProeBOMTable(NmCommandBean nmcommandbean, String tableFilePath) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doUpdateLineNumberFromProeBOMTable()---tableFilePath=" + tableFilePath);
        if (!RemoteMethodServer.ServerFlag)
        {
            try
            {
                Class aclass[] =
                { NmCommandBean.class, String.class };
                Object aobj[] =
                { nmcommandbean, tableFilePath };
                return (NmChangeModel[]) RemoteMethodServer.getDefault().invoke("doUpdateLineNumberFromProeBOMTable", CLASSNAME, null, aclass, aobj);
            }
            catch (InvocationTargetException invocationtargetexception)
            {
                Throwable throwable = invocationtargetexception.getTargetException();
                if (throwable instanceof WTException)
                {
                    throw (WTException) throwable;
                }
                else
                {
                    Object aobj2[] =
                    { "doUpdateLineNumberFromProeBOMTable" };
                    throw new WTException(throwable, "wt.fc.fcResource", "0", aobj2);
                }
            }
            catch (RemoteException remoteexception)
            {
                Object aobj1[] =
                { "doImportMaterialListFromExcel" };
                throw new WTException(remoteexception, "wt.fc.fcResource", "0", aobj1);
            }
        }
        NmOid nmoid1 = nmcommandbean.getPrimaryOid();
        WTPart contextPart = null;
        if (nmoid1 != null)
        {
            contextPart = (WTPart) nmoid1.getRef();
            System.out.println("    contextPart=" + contextPart.getIdentity());
        }

        Transaction trx = null;
        try
        {
            trx = new Transaction();
            trx.start();
            //获取子件
            Hashtable childrenCache = new Hashtable(); //key= bom string; value=bom items list(Vector);
            WTPartStandardConfigSpec config = WTPartStandardConfigSpec.newWTPartStandardConfigSpec((View) contextPart.getView().getObject(), null);
            QueryResult subNodes = WTPartHelper.service.getUsesWTParts(contextPart, config);
            while (subNodes.hasMoreElements())
            {
                Persistable aSubNodePair[] = (Persistable[]) subNodes.nextElement();
                WTPartUsageLink link = (WTPartUsageLink) aSubNodePair[0];
                WTPart child = null;
                if (aSubNodePair[1] instanceof WTPart)
                {
                    child = (WTPart) aSubNodePair[1];
                }
                else if (aSubNodePair[1] instanceof WTPartMaster)
                {
                    WTPartMaster wtpartmaster = (WTPartMaster) aSubNodePair[1];
                    throw new WTException("    零部件 " + wtpartmaster.getIdentity() + " 没有合适的版本不进行处理!");
                }
                //需要清除行号
                link.setLineNumber(null);
                PersistenceServerHelper.manager.update(link);
                if (VERBOSE)
                    System.out.println("    已清除 " + child.getIdentity() + " 的行号.");

                Hashtable ibaValues = IBAUtil.getIBAValues(child);
                String codeName = (String) ibaValues.get("CODENAME");
                String partName = child.getName();
                codeName = codeName.trim();
                partName = partName.trim();
                String material = (String) ibaValues.get("MATERIAL");
                String comment = (String) ibaValues.get("COMMENT");
                if (material == null)
                    material = "";
                if (comment == null)
                    comment = "";
                comment = comment.trim();
                if (VERBOSE)
                    System.out.println("    comment length=" + comment.length());
                Double qty = new Double(link.getQuantity().getAmount());
                String quantity = "" + qty.intValue();
                String bomItemString = codeName + "," + partName + "," + material + "," + comment;
                if (VERBOSE)
                    System.out.println("	bom item string=" + bomItemString);
                Vector bomItems = (Vector) childrenCache.get(bomItemString);
                if (bomItems == null)
                {
                    bomItems = new Vector();
                    bomItems.add(link);
                }
                else
                {
                    bomItems.add(link);
                    if (VERBOSE)
                        System.out.println("	发现相同BOM项.");
                }
                childrenCache.put(bomItemString, bomItems);
            }
            if (VERBOSE)
                System.out.println("	子件获取完成，开始读取table文件.");
            String line;
            int index = 0;
            InputStreamReader inputst = null;
            FileInputStream input = new FileInputStream(tableFilePath);
            inputst = new InputStreamReader(input, "UTF-8");

            BufferedReader in = new BufferedReader(inputst);
            while ((line = in.readLine()) != null)
            {
                index++;
                if (VERBOSE)
                    System.out.println("    --------开始处理第" + index + "行==" + line);
                String split[] = line.split(",");
                if (split[0] == null || split[0].length() <= 0)
                {
                    break;
                }
                String lineNumber = split[0];
                String codeName = split[1];
                String partName = split[2];
                String quantity = split[3];

                String material = split[4];
                String comment = "";
                if (split.length >= 8)
                    comment = split[7];
                if (comment == null)
                    comment = "";
                comment = comment.trim();
                if (VERBOSE)
                    System.out.println("    csv trimed comment length=" + comment.length());
                codeName = codeName.trim();
                partName = partName.trim();
                try
                {
                    long value = Long.parseLong(lineNumber);
                }
                catch (Exception exception)
                {
                    lineNumber = lineNumber.substring(1);
                }
                if (VERBOSE)
                    System.out.println("	lineNumber=" + lineNumber + "; codeName=" + codeName + "; partName=" + partName + "; quantity=" + quantity);
                String bomItemString = codeName + "," + partName + "," + material + "," + comment;
                if (VERBOSE)
                    System.out.println("    csv bom item string=" + bomItemString);
                Vector bomItems = (Vector) childrenCache.get(bomItemString);
                if (bomItems == null)
                {
                    throw new WTException("第" + index + "行出错：没有找到匹配的BOM项.");
                }
                else
                {
                    if (VERBOSE)
                        System.out.println("    找到了匹配的BOM项" + bomItems.size() + "个.");
                    if (bomItems.size() > 1)
                    {
                        throw new WTException("第" + index + "行出错：找到了匹配的BOM项" + bomItems.size() + "个,匹配BOM项数大于1,不能更新BOM!");
                    }
                    //更新行号与数量
                    WTPartUsageLink link = (WTPartUsageLink) bomItems.elementAt(0);
                    Quantity qty = link.getQuantity();
                    qty.setAmount(Double.parseDouble(quantity));
                    link.setLineNumber(LineNumber.newLineNumber(Long.parseLong(lineNumber)));
                    link.setQuantity(qty);
                    PersistenceServerHelper.manager.update(link);
                    if (VERBOSE)
                        System.out.println("	已更新一个BOM项.");
                }
            }
            trx.commit();
            trx = null;
            in.close();
        }
        catch (Exception exception)
        {
            throw new NmException(exception);
        }
        finally
        {
            if (trx != null)
            {
                trx.rollback();
            }
        }
        return null;
    }

//    /**
//     *对比多个产品(或部件)的零件汇总数据比较表
//     * @param nmcommandbean
//     * @param encodedConfigSpec
//     * @return
//     * @throws WTException
//     */
//    public static String getComponentsListCompareTable(NmCommandBean nmcommandbean, String encodedConfigSpec) throws WTException
//    {
//        if (!RemoteMethodServer.ServerFlag)
//        {
//            try
//            {
//                Class aclass[] =
//                { NmCommandBean.class, String.class };
//                Object aobj[] =
//                { nmcommandbean, encodedConfigSpec };
//                return (String) RemoteMethodServer.getDefault().invoke("getComponentsListCompareTable", CLASSNAME, null, aclass, aobj);
//            }
//            catch (Exception exception)
//            {
//                throw new WTException(exception);
//            }
//        }
//        int depth = -1;
//        boolean flag = false;
//        //NmOid nmoid = nmcommandbean.getActionOid();
//        ArrayList selected = nmcommandbean.getSelectedInOpener();
//        Locale locale = nmcommandbean.getLocale();
//        if (VERBOSE)
//            System.out.println("	selectd parts count=" + selected.size());
//        HashMap datas = new HashMap();
//        for (int i = 0; i < selected.size(); i++)
//        {
//            NmContext context = (NmContext) selected.get(i);
//            NmOid nmoid = context.getTargetOid();
//            if (VERBOSE)
//                System.out.println("	target nmoid=" + nmoid);
//            HashMap hashmap = null;
//            //ObjectIdentifier objectidentifier = ObjectIdentifier.newObjectIdentifier(nmoid.getReferencedClassString());
//            //Iterated iterated = (Iterated) (Iterated) ObjectReference.newObjectReference(objectidentifier).getObject();
//            Iterated iterated = (Iterated) nmoid.getRef();
//            if (iterated instanceof WTPart)
//            {
//                WTPart wtpart = (WTPart) iterated;
//                hashmap = BOMReportService.getMultiLevelComponentList(wtpart, encodedConfigSpec, Integer.valueOf(depth), flag);
//                if (VERBOSE)
//                {
//                    System.out.println("	the part is " + wtpart.getDisplayIdentifier());
//                    System.out.println("	the component list count=" + hashmap.size());
//                }
//            }
//            else if (iterated instanceof WTProductConfiguration)
//            {
//                WTProductConfiguration wtproductconfiguration = (WTProductConfiguration) iterated;
//                hashmap = BOMReportService.getMultiLevelComponentList(wtproductconfiguration, Integer.valueOf(depth));
//            }
//            else if (iterated instanceof WTProductInstance2)
//            {
//                WTProductInstance2 wtproductinstance2 = (WTProductInstance2) iterated;
//                hashmap = BOMReportService.getMultiLevelComponentList(wtproductinstance2, encodedConfigSpec, Integer.valueOf(depth));
//            }
//            //ArrayList rows = getComponentsListRows(hashmap);
//            datas.put(iterated, hashmap);
//        }
//        StringWriter tableHtml = new StringWriter();
//        PrintWriter pw = new PrintWriter(tableHtml);
//        //打印比较表格
//        //打印表头
//        pw.println("<table border=\"1\"><tr>");
//        pw.println("<th bordercolor=\"#000000\">子件/产品(或部件)</th>");
//        Iterator iterator = datas.keySet().iterator();
//        while (iterator.hasNext())
//        {
//            WTPart part = (WTPart) iterator.next();
//            pw.println("<th bordercolor=\"#000000\">" + part.getDisplayIdentifier() + "</th>");
//        }
//        pw.println("</tr>");
//        //开始获取所有的子件项
//        Vector targets = new Vector(datas.keySet());
//        HashMap items = new HashMap();
//        for (int i = 0; i < targets.size(); i++)
//        {
//            WTPart element = (WTPart) targets.elementAt(i);
//            HashMap parts = (HashMap) datas.get(element);
//            items.putAll(parts);
//        }
//
//        Vector parts = new Vector(items.keySet());
//        for (int i = 0; i < parts.size(); i++)
//        {
//            WTPart part = (WTPart) parts.elementAt(i);
//            //开始打印数据行
//            boolean bSame = true;
//            String compareContent = "";
//            String trContent = "<td bordercolor=\"#000000\">" + part.getDisplayIdentifier() + "</td>";
//            for (int j = 0; j < targets.size(); j++)
//            {
//                WTPart element = (WTPart) targets.elementAt(j);
//                HashMap partsMap = (HashMap) datas.get(element);
//                HashMap partInfo = (HashMap) partsMap.get(part);
//                String content = "";
//                if (partInfo != null)
//                {
//                    Iterator keys = partInfo.keySet().iterator();
//                    while (keys.hasNext())
//                    {
//                        Object key = keys.next();
//                        Double double1 = Double.valueOf(0.0D);
//                        QuantityUnit quantityunit = null;
//                        if (key instanceof RecursiveStructureError)
//                        {
//                            quantityunit = QuantityUnit.EA;
//                        }
//                        else
//                        {
//                            double1 = (Double) partInfo.get(key);
//                            quantityunit = (QuantityUnit) key;
//                        }
//                        /*
//				        ReportInfo reportinfo = createReportInfo(quantityunit, double1);
//				        ReportRow reportrow = new ReportRow((WTPart) part, reportinfo);
//				        */
//                        if (content.length() <= 0)
//                            content = double1 + quantityunit.getDisplay(locale);
//                        else
//                            content = "<p>" + content + "<p>" + double1 + quantityunit.getDisplay(locale);
//                    }
//                }
//                if (j == 0)
//                {
//                    compareContent = content;
//                }
//                else
//                {
//                    if (!compareContent.equals(content))
//                    {
//                        bSame = false;
//                    }
//                }
//                String tdContent = "<td bordercolor=\"#000000\">" + content + "</td>";
//                trContent = trContent + tdContent;
//            }
//
//            if (bSame)
//                pw.println("<tr>");
//            else
//                pw.println("<tr class=\"differentRow\">");
//            pw.println(trContent);
//            pw.println("</tr>");
//        }
//        //结束打印表头
//        pw.println("</table>");
//        pw.flush();
//        return tableHtml.toString();
//    }

    /**
     *递归计算BOM中零件的数量,并行程报表行
     * @param hashmap
     * @return
     * @throws WTException
     */
    protected static ArrayList getComponentsListRows(HashMap hashmap) throws WTException
    {
        Set set = hashmap.keySet();
        ArrayList arraylist = new ArrayList();
        for (Iterator iterator = set.iterator(); iterator.hasNext(); )
        {
            Object part = iterator.next();
            HashMap hashmap1 = (HashMap) hashmap.get(part);
            Set set1 = hashmap1.keySet();
            Iterator iterator1 = set1.iterator();
            while (iterator1.hasNext())
            {
                Object obj1 = iterator1.next();
                Double double1 = Double.valueOf(0.0D);
                QuantityUnit quantityunit = null;
                if (obj1 instanceof RecursiveStructureError)
                {
                    quantityunit = QuantityUnit.EA;
                }
                else
                {
                    double1 = (Double) hashmap1.get(obj1);
                    quantityunit = (QuantityUnit) obj1;
                }
                ReportInfo reportinfo = createReportInfo(quantityunit, double1);
                ReportRow reportrow = new ReportRow((WTPart) part, reportinfo);
                if (obj1 instanceof RecursiveStructureError)
                {
                    reportinfo.setRecursiveChild(true);
                }
                arraylist.add(reportrow);
            }
        }

        return arraylist;
    }
    /**
     *创建报表信息封装的对象;主要是针对多层物料清单的报表程序;
     * @param quantityunit
     * @param double1
     * @return
     */
    private static ReportInfo createReportInfo(QuantityUnit quantityunit, Double double1)
    {
        ReportInfo reportinfo = new ReportInfo();
        reportinfo.setQuantity(double1);
        reportinfo.setUnits(quantityunit);
        return reportinfo;
    }

    /**
     *构造从工具条引发刷新页面组件的方法;
     * @param nmcommandbean
     * @param url
     * @throws WTException
     */
    private static void refreshFromToolbarAction(NmCommandBean nmcommandbean, URL url) throws WTException
    {
        try
        {
            nmcommandbean.getResponse().sendRedirect(url.toExternalForm());

        }
        catch (IOException ioexception)
        {
            ioexception.printStackTrace();
            throw new WTException(ioexception);
        }
    }

    private static void refreshFromPopup(NmCommandBean nmcommandbean, URL url) throws WTException
    {
        String s;
        JSPFeedback jspfeedback;
        NmFeedbackSpec nmfeedbackspec;
        s = url.toExternalForm();
        jspfeedback = null;
        nmfeedbackspec = null;
        try
        {
            jspfeedback = nmcommandbean.initializeFeedback((new StringBuilder()).append("eai-").append(System.currentTimeMillis()).toString());
            nmfeedbackspec = jspfeedback.getSpec();
        }
        catch (WTException wtexception)
        {
            if (nmfeedbackspec != null)
            {
                nmfeedbackspec.setException(wtexception);
            }
            throw wtexception;
        }
        finally
        {
            nmcommandbean.finalizeFeedback(jspfeedback, s);
        }
    }

    /**
     *为输出的文件构造下载链接
     * @param file
     * @param s
     * @return
     * @throws WTException
     */
    private static URL constructOutputURL(File file, String s) throws WTException
    {
        if (VERBOSE)
        {
            System.out.println("Enter constructOutputURL -->");
        }
        try
        {
            WTPrincipal wtprincipal = SessionHelper.manager.getPrincipal();
            String s1 = wtprincipal.getName();
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("userName: ").append(s1).toString());
            }
            HashMap hashmap = new HashMap();
            String s2 = null;
            if (file != null)
            {
                if (VERBOSE)
                {
                    System.out.println((new StringBuilder()).append("tmpFile: ").append(file.getName()).toString());
                }
                s2 = file.getCanonicalPath();
                if (VERBOSE)
                {
                    System.out.println((new StringBuilder()).append("tmpName: ").append(s2).toString());
                }
            }
            else
            {
                throw new NmException("com.ptc.netmarkets.nmixb.nmixbResource", "6262", null);
            }
            hashmap.put("fname", s2);
            hashmap.put("userName", s1);
            if (VERBOSE)
            {
                System.out.println("securing the download operation");
            }
            SessionContext sessioncontext = new SessionContext();
            sessioncontext.register();
            String s3 = sessioncontext.getSessionId();
            if (s3 == null)
            {
                throw new NmException("com.ptc.netmarkets.nmixb.nmixbResource", "6263", null);
            }
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("sessId: ").append(s3).toString());
            }
            hashmap.put("sessId", s3);
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("fname: ").append(s).toString());
                System.out.println("Done securing the download operation");
            }
            URLFactory urlfactory = new URLFactory();
            URL url = GatewayServletHelper.buildAuthenticatedURL(urlfactory, "com.ptc.netmarkets.actionitem.StandardNmActionItemService", "redirectRecipient", s, hashmap);
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("<-- Exit constructOutputURL, url: ").append(url.toExternalForm()).append(", file = ").append(file).toString());
            }
            return url;
        }
        catch (MalformedURLException malformedurlexception)
        {
            throw new NmException(malformedurlexception);
        }
        catch (IOException ioexception)
        {
            throw new NmException(ioexception);
        }
    }

    /**
     *根据当前对象获取其字符串与实数类型的IBA属性；该方法用于“清理软属性”的操作
     * @param nmcommandbean
     * @return
     * @throws WTException
     */
    public static QueryResult getIBAValues(NmCommandBean nmcommandbean) throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".getIBAValues");
        QueryResult qr = null;
        WTObject ibaHolder = (WTObject) nmcommandbean.getActionOid().getRefObject();
        Class valueClass = StringValue.class;
        QuerySpec qs = null;

        qs = new QuerySpec(valueClass);
        SearchCondition sc = new SearchCondition(valueClass, "theIBAHolderReference.key.classname", SearchCondition.EQUAL, ibaHolder.getClass().getName());
        qs.appendSearchCondition(sc);

        qs.appendAnd();
        ReferenceFactory rf = new ReferenceFactory();
        ObjectIdentifier objId = PersistenceHelper.getObjectIdentifier(ibaHolder);
        SearchCondition sc2 = new SearchCondition(valueClass, "theIBAHolderReference.key", SearchCondition.EQUAL, objId);
        qs.appendSearchCondition(sc2);

        qr = PersistenceHelper.manager.find(qs);
        if (VERBOSE)
        {
            System.out.println(">>>getIBAValues---String value queryResult size=" + qr.size());
        }

        QueryResult qr2 = null;
        Class valueClass2 = FloatValue.class;
        QuerySpec qs2 = null;

        qs2 = new QuerySpec(valueClass2);
        SearchCondition sc21 = new SearchCondition(valueClass2, "theIBAHolderReference.key.classname", SearchCondition.EQUAL, ibaHolder.getClass().getName());
        qs2.appendSearchCondition(sc21);

        qs2.appendAnd();
        SearchCondition sc22 = new SearchCondition(valueClass2, "theIBAHolderReference.key", SearchCondition.EQUAL, objId);
        qs2.appendSearchCondition(sc22);

        qr2 = PersistenceHelper.manager.find(qs2);

        if (VERBOSE)
        {
            System.out.println(">>>getIBAValues---Float value queryResult size=" + qr.size());
        }

        qr.append(qr2.getObjectVectorIfc());


        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".getIBAValues---total count=" + qr.size());
        return qr;
    }
    
	/**
	 * 根据所输入的条件选择名称或者全名符合条件的用户
	 * 
	 * @param findString 查找的字符串
	 * @return  Vector 用户列表
	 * @exception WTException windchill基本的例外
	 *    	
	 * <br><br>
	 * <b>Revision History</b>
	 * <br><b>Rev:</b> 1.0  2007-9-20, Lauren
	 * <br><b>Comment:</b> Initial release.
	 **/
	public static Vector getUserList(String findString)
		throws WTException
	{
		if(findString==null)
			return null;
		if(findString.trim().length()==0)
			findString = "*";
		Vector userList = new Vector();		
		WTUser user = null;
		Enumeration userList1 =  OrganizationServicesHelper.manager.findLikeUser("name", findString);
		while(userList1!=null && userList1.hasMoreElements())
		{
			user = (WTUser)userList1.nextElement();
			System.out.println("是否为离职人员：" + OrgUtil.isMemberOfGroup("离职", user));
			//过滤掉离职组的人员  add by xuge_ning
			if(!OrgUtil.isMemberOfGroup("离职", user))
				userList.add(user);
		}
		Enumeration userList2 =  OrganizationServicesHelper.manager.findLikeUser("fullName", findString);
		while(userList2!=null && userList2.hasMoreElements())
		{
			user = (WTUser)userList2.nextElement();
			if(!userList.contains(user) && !OrgUtil.isMemberOfGroup("离职", user))
				userList.add(user);
		}
		
		return userList;
	}

}
